package infraestructura;

import java.util.ArrayList;
import java.util.List;
import modelo.Product;

public class ProductMemoryPersistence implements ProductPersistence {

    private List<Product> products = new ArrayList();
    private static ProductMemoryPersistence persistence = null;
    
    private ProductMemoryPersistence() {
        products.add(new Product(1, "Converse", "Converse All Star",
                "NEW AND LONG CONVERSE ALL STAR", 59.99, 5));
    }
    
    public static ProductPersistence getPersistenceManager() {
        if (persistence == null) {
            persistence = new ProductMemoryPersistence();
        }
        return persistence;
    }
    
    @Override
    public boolean exists(String name) {
        for(Product product : products) {
            if (product.getName() == null ? name == null : product.getName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean exists(int id) {
        for(Product product : products) {
            if (product.getId() == id) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getTheId(String name) {
        for(Product product : products) {
            if (product.getName() == null ? name == null : product.getName().equals(name)) {
                return product.getId();
            }
        }
        throw new IllegalArgumentException("El producto no existe, debería haberse validado antes");
    }

    @Override
    public Product getProduct(int id) {
        for(Product product : products) {
            if (product.getId() == id) {
                return product;
            }
        }
        throw new IllegalArgumentException("El producto no existe, debería haberse validado antes");
    }

    @Override
    public void createProduct(Product product) {
        products.add(product);
    }

    @Override
    public void updateProduct(int id, Product product) {
        deleteProduct(id);
        createProduct(product);
    }

    @Override
    public void deleteProduct(int id) {
        Product toBeDeleted = getProduct(id);
        products.remove(toBeDeleted);
    }

    @Override
    public List<Product> getALLTheProducts() {
        return products;
    }

    @Override
    public void updateStock(int id, int cantidad) {
        Product producto = getProduct(id);
        producto.setStock(producto.getStock()-cantidad);
        updateProduct(id, producto);
        
    }
    
}
